package com.china08.yxyapi.api.manage.tec.teaching.resource.myresource;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceBookContent;
import com.china08.yxyapi.entity.db.res.YxyResSemester;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResSemesterRepository;
import com.china08.yxyapi.service.yxyresource.YxyResourceService;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.EsResourcePvUpdateUtil;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.SpringContextUtil;
import com.china08.yxyapi.util.YxyResUtil;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class MyResourceDetailController extends YxyApiBaseController {

    @Autowired
    private YxyResUtil YxyResUtil;

    @Autowired
    private YxyResourceService yrs;

    @Autowired
    private YxyResResourceRepository yrrr;

    @ApiOperation(value = "老师资源详情")
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/tec/teaching/resource/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel find(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel)
            throws IllegalAccessException, InvocationTargetException {
        RespModel model = new RespModel();
        ElasticYxyResResource elasticYxyResResource = yrs.findById(reqModel.id);
        Assert.notNull(elasticYxyResResource, "找不到资源，请刷新页面");
        YxyResResource resource = yrrr.findById(reqModel.id);
        Assert.notNull(resource, "找不到资源，请刷新页面");
        resource.setPv(resource.getPv() + 1);
        yrrr.save(resource);
        BeanUtils.copyProperties(model, elasticYxyResResource);
        if (elasticYxyResResource.getUploadTime() != null) {
            model.uploadTimeFormat = DateToolUtils.format(elasticYxyResResource.getUploadTime(),
                    DateToolUtils.FORMAT_SHORT_YMD);
        }
        model.setMessage("成功");
        // 资源下载
        String download = YxyResUtil.getDownloadUrl(reqModel.id);
        model.setDownloadLocation(download);
        model.setPreview(YxyResUtil.getPreviewUrl(reqModel.id));
        model.setBookContentNames(elasticYxyResResource.getBookContentNameList());
        model.setPhaseId(
                elasticYxyResResource.getPhaseIdList().size() > 0 ? elasticYxyResResource.getPhaseIdList().get(0) : "");
        model.setPhaseName(elasticYxyResResource.getPhaseNameList().size() > 0
                ? elasticYxyResResource.getPhaseNameList().get(0) : "");
        model.setSubjectId(elasticYxyResResource.getSubjectIdList().size() > 0
                ? elasticYxyResResource.getSubjectIdList().get(0) : "");
        model.setSubjectName(elasticYxyResResource.getSubjectNameList().size() > 0
                ? elasticYxyResResource.getSubjectNameList().get(0) : "");
        model.setExtion(elasticYxyResResource.getExtension());
        EsResourceUpdateUtil.updateEsResoure(resource.getId());
        EsResourcePvUpdateUtil.updateEsResoure(resource.getId() + "_1");
        return model;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String id;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(id, null), "请指定资源");
        }

    }

    protected static class BookContentRespModel {
        public String id;
        public String pId;
        public String name;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getpId() {
            return pId;
        }

        public void setpId(String pId) {
            this.pId = pId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

    public static class RespModel extends YxyApiRespModel {
        // id
        public String id;
        // 标题
        public String title;

        // 类型
        public String typeName;

        // 類型
        public String typeId;

        // 上传人名
        public String uploaderName;

        // 上传者学校明天
        public String uploaderSchoolName;

        // 审核人
        public String auditUserName;

        // 审核学校
        public String auditSchoolName;

        // 资源简介
        public String intro;

        // 文件的状态信息 0初始上传， 1 转码中 ，2 转码成功 ，3 转码失败
        public Integer convertStatus = 0;

        /**
         * 文件路径
         */
        public String location;

        public String formatId;

        public String formatName;

        // 上传时间
        public String uploadTimeFormat = "";

        // 所属目录名称
        public List<String> bookContentNames;

        public String downloadLocation = "";

        // 预览
        public String preview = "";

        // 审核状态 0：待审核 1：已通过 2：未通过 3：已下架
        public Integer status = 0;
        /**
         * 查看范围 0：私有 1：学校 2： 教育云
         */
        public Integer viewScope;

        public String subjectId;

        public String subjectName;

        public String phaseId;

        public String phaseName;

        public List<String> versionIdList = new ArrayList<>();

        public List<String> versionNameList = new ArrayList<>();

        public List<String> semesterIdList = new ArrayList<>();
        public List<SemestersModel> semesters = new ArrayList<>();

        public List<String> semesterNameList = new ArrayList<>();
        public List<Object> bookContents = new ArrayList<>();

        public List<String> bookContentNameList = new ArrayList<>();

        public List<String> bookIdList = new ArrayList<>();

        public List<Map<String, Object>> catalogList = new ArrayList<>();

        public List<String> bookContentIdList = new ArrayList<String>();

        public List<String> pureBookContentIdList = new ArrayList<String>();
        public String extion;
        // get and set

        //
        public List<Map<String, Object>> getCatalogList() {

            YxyResBookRepository yrbr = SpringContextUtil.getBean(YxyResBookRepository.class);

            YxyResSemesterRepository yxyResSemesterRepository = SpringContextUtil
                    .getBean(YxyResSemesterRepository.class);
            YxyResBookContentsRepository yrbcr = SpringContextUtil.getBean(YxyResBookContentsRepository.class);
            // Collections.reverse(this.semesterIdList);
            // Collections.reverse(this.getBookIdList());
            List<YxyResResourceBookContent> aBookContents = SpringContextUtil
                    .getBean(YxyResResourceBookContentRepository.class).findByResourceId(this.id);
            this.pureBookContentIdList = aBookContents.stream().map(x -> x.getBookContentId())
                    .collect(Collectors.toList());
            for (YxyResResourceBookContent yxyResResourceBookContent : aBookContents) {
                Map<String, Object> map = new HashMap<>();
                map.put("version", yxyResResourceBookContent.getVersionId());// versionId
                map.put("versionName", yxyResResourceBookContent.getVersionName());// versionName
                map.put("semester", yxyResResourceBookContent.getSemesterId());// semesterId
                List<YxyResBook> books = new ArrayList<YxyResBook>();
                books = yrbr.findBySubjectIdAndVersionIdAndPhaseIdAndStatus(this.getSubjectId(),
                        yxyResResourceBookContent.getVersionId(), yxyResResourceBookContent.getPhaseId(), 1);
                if (books.size() > 0) {
                    List<String> semesterIds = books.stream().map(x -> x.getSemersterId()).collect(Collectors.toList());

                    List<YxyResSemester> yxyResSemesters = yxyResSemesterRepository
                            .findByIdInAndStatusOrderByOrderNum(semesterIds, 1);
                    List<SemestersModel> list = new ArrayList<MyResourceDetailController.SemestersModel>();
                    for (YxyResSemester yxyResSemester : yxyResSemesters) {
                        YxyResBook yxyResType = books.stream()
                                .filter(x -> StringUtils.equals(x.getSemersterId(), yxyResSemester.getId())).findFirst()
                                .get();
                        if (yxyResType != null) {
                            SemestersModel model = new SemestersModel();
                            model.id = yxyResType.getSemersterId();
                            model.name = yxyResType.getSemersterName();
                            model.bookId = yxyResType.getId();
                            list.add(model);
                        }
                    }
                    this.semesters = list;
                }

                map.put("semesters", this.semesters);// semesters
                map.put("semesterName", yxyResResourceBookContent.getSemesterName());// semesterName
                List<YxyResBookContents> listcoContents = yrbcr
                        .findByBookIdAndIsViewOrderByOrderNum(yxyResResourceBookContent.getBookId(), 1);
                List<BookContentRespModel> list = new ArrayList<MyResourceDetailController.BookContentRespModel>();
                for (YxyResBookContents yxyResBookContents : listcoContents) {
                    BookContentRespModel bookContentRespModel = new BookContentRespModel();
                    bookContentRespModel.id = yxyResBookContents.getId();
                    bookContentRespModel.name = yxyResBookContents.getName();
                    bookContentRespModel.pId = yxyResBookContents.getpId();
                    list.add(bookContentRespModel);
                }

                map.put("bookcontent", yxyResResourceBookContent.getBookContentId());// bookcontentid
                map.put("bookcontents", list);// bookcontentid
                YxyResBookContents bookContent = yrbcr.findById(yxyResResourceBookContent.getBookContentId());
                String bookcontentname = bookContent != null ? bookContent.getName() : "";
                map.put("bookcontentName", bookcontentname);// bookcontentName
                                                            // p-s-v-bc
                map.put("bookcontentNames", yxyResResourceBookContent.getBookContentName());// bookcontentNames
                this.catalogList.add(map);
            }
            return catalogList;
        }

        public String getExtion() {
            return extion;
        }

        public void setExtion(String extion) {
            this.extion = extion;
        }

        public String getTypeId() {
            return typeId;
        }

        public void setTypeId(String typeId) {
            this.typeId = typeId;
        }

        public List<String> getPureBookContentIdList() {
            return pureBookContentIdList;
        }

        public void setPureBookContentIdList(List<String> pureBookContentIdList) {
            this.pureBookContentIdList = pureBookContentIdList;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getTypeName() {
            return typeName;
        }

        public void setTypeName(String typeName) {
            this.typeName = typeName;
        }

        public String getUploaderName() {
            return uploaderName;
        }

        public void setUploaderName(String uploaderName) {
            this.uploaderName = uploaderName;
        }

        public String getUploaderSchoolName() {
            return uploaderSchoolName;
        }

        public void setUploaderSchoolName(String uploaderSchoolName) {
            this.uploaderSchoolName = uploaderSchoolName;
        }

        public String getAuditUserName() {
            return auditUserName;
        }

        public void setAuditUserName(String auditUserName) {
            this.auditUserName = auditUserName;
        }

        public String getAuditSchoolName() {
            return auditSchoolName;
        }

        public void setAuditSchoolName(String auditSchoolName) {
            this.auditSchoolName = auditSchoolName;
        }

        public String getIntro() {
            return intro;
        }

        public void setIntro(String intro) {
            this.intro = intro;
        }

        public Integer getConvertStatus() {
            return convertStatus;
        }

        public void setConvertStatus(Integer convertStatus) {
            this.convertStatus = convertStatus;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public String getFormatId() {
            return formatId;
        }

        public void setFormatId(String formatId) {
            this.formatId = formatId;
        }

        public String getFormatName() {
            return formatName;
        }

        public void setFormatName(String formatName) {
            this.formatName = formatName;
        }

        public String getUploadTimeFormat() {
            return uploadTimeFormat;
        }

        public void setUploadTimeFormat(String uploadTimeFormat) {
            this.uploadTimeFormat = uploadTimeFormat;
        }

        public List<String> getBookContentNames() {
            return bookContentNames;
        }

        public void setBookContentNames(List<String> bookContentNames) {
            this.bookContentNames = bookContentNames;
        }

        public String getDownloadLocation() {
            return downloadLocation;
        }

        public void setDownloadLocation(String downloadLocation) {
            this.downloadLocation = downloadLocation;
        }

        public String getPreview() {
            return preview;
        }

        public void setPreview(String preview) {
            this.preview = preview;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public Integer getViewScope() {
            return viewScope;
        }

        public void setViewScope(Integer viewScope) {
            this.viewScope = viewScope;
        }

        public String getSubjectId() {
            return subjectId;
        }

        public void setSubjectId(String subjectId) {
            this.subjectId = subjectId;
        }

        public String getSubjectName() {
            return subjectName;
        }

        public void setSubjectName(String subjectName) {
            this.subjectName = subjectName;
        }

        public String getPhaseId() {
            return phaseId;
        }

        public void setPhaseId(String phaseId) {
            this.phaseId = phaseId;
        }

        public String getPhaseName() {
            return phaseName;
        }

        public void setPhaseName(String phaseName) {
            this.phaseName = phaseName;
        }

        public List<String> getVersionIdList() {
            return versionIdList;
        }

        public void setVersionIdList(List<String> versionIdList) {
            this.versionIdList = versionIdList;
        }

        public List<String> getVersionNameList() {
            return versionNameList;
        }

        public void setVersionNameList(List<String> versionNameList) {
            this.versionNameList = versionNameList;
        }

        public List<String> getSemesterIdList() {
            return semesterIdList;
        }

        public void setSemesterIdList(List<String> semesterIdList) {
            this.semesterIdList = semesterIdList;
        }

        public List<SemestersModel> getSemesters() {
            return semesters;
        }

        public void setSemesters(List<SemestersModel> semesters) {
            this.semesters = semesters;
        }

        public List<String> getSemesterNameList() {
            return semesterNameList;
        }

        public void setSemesterNameList(List<String> semesterNameList) {
            this.semesterNameList = semesterNameList;
        }

        public List<Object> getBookContents() {
            return bookContents;
        }

        public void setBookContents(List<Object> bookContents) {
            this.bookContents = bookContents;
        }

        public List<String> getBookContentNameList() {
            return bookContentNameList;
        }

        public void setBookContentNameList(List<String> bookContentNameList) {
            this.bookContentNameList = bookContentNameList;
        }

        public List<String> getBookIdList() {
            return bookIdList;
        }

        public void setBookIdList(List<String> bookIdList) {
            this.bookIdList = bookIdList;
        }

        public void setCatalogList(List<Map<String, Object>> catalogList) {
            this.catalogList = catalogList;
        }

        public List<String> getBookContentIdList() {
            return bookContentIdList;
        }

        public void setBookContentIdList(List<String> bookContentIdList) {
            this.bookContentIdList = bookContentIdList;
        }

    }

    protected static class SemestersModel {
        public String id;
        public String name;
        public String bookId;
    }
}
